module Permissible
	
	# Check if the given action for the given namespace is permissible. May also be limited to a 
	# certain resource with the given ID.
	def permissible?(action=params[:action], resource_id=params[:id], namespace=nil)
		# The Super Mighty Admin can do it all!
		return true if current_user.admin?
		
		# Convention: No "Controller" at the end of the namespace name for permissions
		namespace ||= self.class.name.gsub(/Controller$/, "")
		
		general = "#{namespace}.#{action}"
		
		if has_permission?(general)
			return true
		elsif resource_id.nil?
			return false
		end
		
		resource_specific = "#{general}##{resource_id}"
		has_permission?(resource_specific)
	end
	
	# Helper method to be called as before_filter
	def enforce_access_control(action=params[:action], resource_id=params[:id])
		raise SecurityTransgression unless permissible?(action, resource_id)
	end
	
	# Creates edit, update and destroy permissions for the given resource and owner.
	def create_default_owner_permissions(resource, owner)
		namespace = resource.class.name.pluralize
		
		edit_permission = owner.permissions.build(
			key: "#{namespace}.edit##{resource.id}",
			created_by: owner.id
		)
		edit_permission.translations.build(
			description: 'Permission to view the edit page for the given user.', 
			locale: 'en'
		)
		edit_permission.translations.build(
			description: 'Berechtigung die Bearbeitungsseite zu sehen fuer den gegebenen Benutzer.',
			locale: 'de'
		)
		
		update_permission = owner.permissions.build(
			key: "#{namespace}.update##{resource.id}", 
			created_by: owner.id
		)
		update_permission.translations.build(
			description: 'Permission to update the resource for the given user.', 
			locale: 'en'
		)
		update_permission.translations.build(
			description: 'Berechtigung die Resource zu aktualisieren fuer den gegebenen Benutzer.', 
			locale: 'de'
		)
		
		destroy_permission = owner.permissions.build(
			key: "#{namespace}.destroy##{resource.id}", 
			created_by: owner.id
		)
		destroy_permission.translations.build(
			description: 'Permission to delete the resource for the given user.', 
			locale: 'en'
		)
		destroy_permission.translations.build(
			description: 'Berechtigung die Resource zu loeschen fuer den gegebenen Benutzer.', 
			locale: 'de'
		)	
		
		owner.save
	end
	
	
	private 
	
		# Helper method to be called from Views to explicitly check for permissions of parts on the
		# page
		def has_permission?(key)
			group_permission = current_user.user_group.permissions.where(key: key)
			return true unless group_permission.empty?

			user_permission = current_user.permissions.where(key: key)
			return !(user_permission.empty?)
		end
    
end
